package com.qfedu.knowledge.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.qfedu.knowledge.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @ClassName MyMetaObjHandler
 * @Author ykx
 * @Date 2024/1/9 14:30
 * @Version 1.0
 */
@Component
public class MyMetaObjHandler implements MetaObjectHandler {
    @Autowired
    private SecurityUtils securityUtils;

    @Override
    public void insertFill(MetaObject metaObject) {
        Object creationDate = getFieldValByName("creationDate", metaObject);
        if (Objects.isNull(creationDate)) {
            this.strictInsertFill(metaObject, "creationDate", Date.class, new Date());
        }

        Object lastUpdateDate = getFieldValByName("lastUpdateDate", metaObject);
        if (Objects.isNull(lastUpdateDate)) {
            this.strictInsertFill(metaObject, "lastUpdateDate", Date.class, new Date());
        }

        Object deleteFlag = getFieldValByName("deleteFlag", metaObject);
        if (Objects.isNull(deleteFlag)) {
            this.strictInsertFill(metaObject, "deleteFlag", Integer.class, 0);
        }

        Object createBy = getFieldValByName("createBy", metaObject);
        if (Objects.isNull(createBy)) {
            this.strictInsertFill(metaObject, "createBy", Long.class, securityUtils.getCurrentUser().getId());
        }

        Object lastUpdateBy = getFieldValByName("lastUpdateBy", metaObject);
        if (Objects.isNull(lastUpdateBy)) {
            this.strictInsertFill(metaObject, "lastUpdateBy", Long.class, securityUtils.getCurrentUser().getId());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object lastUpdateDate = getFieldValByName("lastUpdateDate", metaObject);
        if (Objects.isNull(lastUpdateDate)) {
            this.strictInsertFill(metaObject, "lastUpdateDate", Date.class, new Date());
        }
        Object lastUpdateBy = getFieldValByName("lastUpdateBy", metaObject);
        if (Objects.isNull(lastUpdateBy)) {
            this.strictInsertFill(metaObject, "lastUpdateBy", Long.class, securityUtils.getCurrentUser().getId());
        }
    }

}
